"""
@Author：十
@Time：2024/6/21 11:49
@FileName：main.py
@Description：主线程
"""
import calendar
import ctypes
import sys
import datetime

import win32con
import win32gui
from PyQt5 import QtCore
from PyQt5.QtCore import Qt, pyqtSignal, QDateTime, QThread, QTimer
from PyQt5.QtGui import QIcon, QMouseEvent, QFontMetrics, QPalette, QColor
from PyQt5.QtWidgets import QWidget, QApplication, QSystemTrayIcon, QMenu, QAction, QLabel, QMessageBox
from PyQt5.uic import properties
from chinese_calendar import is_workday

from ConfigWindow import ConfigWindow
from WageUI import Ui_Form
from GainsCalculateThread import GainsCalculateThread


class MainWindow(QWidget, Ui_Form):
    # 嵌入桌面
    Signal_Embed_to_Desktop = pyqtSignal()
    # 取消嵌入桌面
    Signal_Restore_to_Normal = pyqtSignal()

    Signal_Calculate = pyqtSignal()

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)

        self.ConfigWindow = ConfigWindow(self)

        self.sec_gain = None

        self.Gains_Calculate_Thread = QThread()
        self.Gains_Calculate_Function = GainsCalculateThread()
        self.Gains_Calculate_Function.moveToThread(self.Gains_Calculate_Thread)
        self.Gains_Calculate_Thread.started.connect(self.Gains_Calculate_Function.run)

        # 固定和取消固定
        self.Signal_Embed_to_Desktop.connect(self.embed_to_desktop)
        self.Signal_Restore_to_Normal.connect(self.restore_to_normal)

        # self.pushButton_Config.clicked.connect(self.ShowConfig)

        # 秒薪配置
        self.ConfigWindow.Signal_Data_Tristate.connect(self.Gains_Calculate)
        # 秒薪显示
        # self.Signal_Calculate.connect(self.Current_Gains)
        self.Gains_Calculate_Function.Signal_Transmit_Gains.connect(self.Gains_Show)
        # 界面初始化
        self.Interface_Init()

        # 定时器
        self.timer = QTimer()
        self.timer.timeout.connect(self.Current_Gains)
        # self.timer.start(1000)

    # 秒薪计算
    def Gains_Calculate(self, config):
        try:
            if not config['Salary'].isnumeric():
                QMessageBox.warning(self, 'Exception', '薪资请输入整数')
                return

            # 秒
            working_time = config['Work_Start'].msecsTo(config['Work_End']) / 1000
            if working_time <= 0:
                QMessageBox.warning(self, 'Exception', '上班时间需要早于下班时间')
                return

            siesta = config['Siesta_Start'].msecsTo(config['Siesta_End']) / 1000
            if siesta < 0:
                QMessageBox.warning(self, 'Exception', '午休开始时间按需要早于结束时间')
                return

            # 工作时长
            duration = working_time - siesta
            # print('工作时长：', duration)
            if duration <= 0:
                QMessageBox.warning(self, 'Exception', '工作时长需要大于午休时长')
                return
            else:
                if config['Vacation'] == 0:
                    workingday = self.Workday_Calculate()
                else:
                    QMessageBox.information(self, 'Information', '其他休假制度还在制作中')
                    return

            # 秒薪 = 月薪 / 工作天数 / （上班时长 - 午休时长）
            self.sec_gain = int(str(config['Salary'])) / workingday / duration
            # print('秒薪:', sec_gain)

            # self.Signal_Calculate.emit()
            self.Gains_Calculate_Function.GetSecGain(self.sec_gain)
            self.Gains_Calculate_Thread.start()

            # 当前时间要减去上下班和午休时间
            # current_time = datetime.datetime.now()
            # clock_9 = datetime.datetime.now().replace(hour=9, minute=0, second=0, microsecond=0)
            # clock_14 = datetime.datetime.now().replace(hour=14, minute=0, second=0, microsecond=0)
            # morning_work = (current_time - clock_9)
            # if current_time > clock_14:
            #     afternoon_work = current_time - clock_14
            #     work_time = afternoon_work + morning_work
            # else:
            #     work_time = morning_work
            # work_time = work_time.total_seconds()
            # gain = work_time * self.sec_gain
            # print('Current Gain::', gain)
        except Exception as e:
            print('Gains Calculate ERROR:', e)

    def Current_Gains(self):
        try:
            current_time = datetime.datetime.now()
            clock_9 = datetime.datetime.now().replace(hour=9, minute=0, second=0, microsecond=0)
            clock_14 = datetime.datetime.now().replace(hour=14, minute=0, second=0, microsecond=0)
            morning_work = (current_time - clock_9)
            if current_time > clock_14:
                afternoon_work = current_time - clock_14
                work_time = afternoon_work + morning_work
            else:
                work_time = morning_work
            work_time = work_time.total_seconds()
            gain = work_time * self.sec_gain
            print('Current Gain:', gain)
            self.label_Gains.setText(str(gain))
            self.timer.start(1000)

            # self.Signal_Transmit_Gains.emit(gain)
        except Exception as e:
            print(e)

    # 接受数据并显示
    def Gains_Show(self, gain):
        self.label_Gains.setText(str(gain))

    # 双休工作日天数计算
    def Workday_Calculate(self):
        workday = 0
        current_time = QDateTime.currentDateTime().date()
        month_start = datetime.datetime.now().date().replace(day=1)
        this_month = calendar.monthrange(current_time.year(), current_time.month())
        # what_day = this_month[0]
        month_len = this_month[1]
        month_end = datetime.datetime.now().date().replace(day=month_len)
        while month_start.__le__(month_end):
            if is_workday(month_start):
                workday += 1
            month_start = month_start + datetime.timedelta(days=1)
        return workday

    # 判断是否是法定节假日
    def isWorkdays(self, date_value):
        if is_workday(date_value):
            return True
        else:
            return False

    # 双击数字呼出配置窗口
    def mouseDoubleClickEvent(self, e):
        try:
            self.ConfigWindow.show()
        except Exception as e:
            print(e)

    # 呼出配置窗口
    def ShowConfig(self):
        self.ConfigWindow.show()

    def Interface_Init(self):
        # 窗体背景透明
        # self.setAttribute(Qt.WA_TranslucentBackground)
        # self.setAttribute(Qt.WA_Mapped | Qt.WA_TranslucentBackground)
        # 没有边框
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.Widget)
        # 没有任务栏
        # self.setWindowFlag(QtCore.Qt.Tool)

        # TODO：会和self.setWindowFlag(Qt.FramelessWindowHint)和self.setAttribute(Qt.WA_TranslucentBackground)同时存在时冲突，导致窗口不可见。并且无法移动窗口，无法改变字体大小使其大于窗口
        self.embed_to_desktop()

    # 嵌入桌面
    def embed_to_desktop(self):
        try:
            # 获取桌面窗口句柄
            hwnd_desktop = ctypes.windll.user32.FindWindowW("Progman", None)
            # 获取当前窗口句柄并进行转换
            hwnd_self = ctypes.c_void_p(int(self.winId()))
            # 将窗口设置为桌面窗口的子窗口
            ctypes.windll.user32.SetParent(hwnd_self, hwnd_desktop)
        except Exception as e:
            print('Embed To Desktop Error:', e)

    # 取消嵌入桌面
    def restore_to_normal(self):
        # 获取当前窗口句柄并进行转换
        hwnd_self = ctypes.c_void_p(int(self.winId()))
        # 将窗口的父窗口设置为 None，恢复默认行为
        ctypes.windll.user32.SetParent(hwnd_self, None)

    # 窗口拖动实现
    def mousePressEvent(self, event: QMouseEvent):
        if event.button() == Qt.LeftButton:
            self.drag_position = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self, event: QMouseEvent):
        if event.buttons() & Qt.LeftButton and self.drag_position is not None:
            self.move(event.globalPos() - self.drag_position)
            event.accept()

    def mouseReleaseEvent(self, event: QMouseEvent):
        self.drag_position = None

    def closeEvent(self, event):
        for widget in QApplication.topLevelWidgets():
            if isinstance(widget, QWidget) and widget != self:
                widget.close()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)

    # 创建系统托盘图标
    icon = QIcon("Icon/icon.png")
    tray_icon = QSystemTrayIcon(icon)
    # 创建右键菜单
    menu = QMenu()
    show_action = QAction("配置", menu)
    quit_action = QAction("退出", menu)
    menu.addAction(show_action)
    menu.addAction(quit_action)
    # 设置右键菜单
    tray_icon.setContextMenu(menu)
    # 显示任务栏图标
    tray_icon.show()


    # 点击右键菜单击的处理函数
    def on_menu_action(action):
        window.show()
        if action == show_action:
            # 处理“Show”菜单项的操作
            pass
        elif action == quit_action:
            # 处理“Quit”菜单项的操作
            pass


    # 绑定菜单项的信号与槽
    show_action.triggered.connect(on_menu_action)
    quit_action.triggered.connect(app.quit)


    # 点击事件函数
    def show_message_box():
        window.show()


    # 托盘点击事件添加监听器
    tray_icon.activated.connect(show_message_box)

    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
